<template>
  <div class="page-container">
    <div class="page-content" v-loading="loading">
      <!--基础配置-->
      <div class="panel-container left-panel" ref="leftPanel">
        <div class="panle-title">基础配置</div>
        <el-form size="mini" ref="elForm" :model="formData" :rules="rules" label-width="100px">
          <div class="panel-block">
            <el-form-item label="尺寸:" prop="basicWidth">
              <div class="line">
                <el-input type="number" @change="handleOnChange('basicWidth')" class="input-small" v-model="formData.basicWidth" placeholder="宽" clearable>
                  <template slot="append">px</template>
                </el-input>
                <el-input type="number" @change="handleOnChange('basicHeight')" class="input-small" v-model="formData.basicHeight" placeholder="高" clearable :style="{ marginLeft: '10px' }">
                  <template slot="append">px</template>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item label="" label-width="0" prop="basicBackground">
              <el-radio-group v-model="formData.basicBackground" size="medium">
                <div class="line">
                  <el-radio class="form-label" key="背景色" label="color">背景色</el-radio>
                  <el-input v-model="formData.basicBackgroundColor" @change="handleBackgroundColorInput" placeholder="请输入" clearable :style="{ width: '30%' }"> </el-input>
                  <ColorPicker ref="ColorPicker" class="color-picker" @confirm="handleBackgroundConfirm" />
                  <el-radio key="背景图" label="img" :style="{ 'margin-right': '10px' }">背景图</el-radio>
                  <el-upload ref="field108" :show-file-list="false" :file-list="fileList" accept="image/jpeg, image/png" action="" :http-request="handleUpload" :before-upload="beforeUpload">
                    <img v-if="formData.basicBackgroundImg && formData.basicBackgroundImg" :src="formData.basicBackgroundImg.replace(/^(http)[s]*(\:\/\/)/, 'https://images.weserv.nl/?url=')" class="img-background" referrer="no-referrer" referrerPolicy="no-referrer" />
                    <i v-else class="el-icon-picture"></i>
                  </el-upload>
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="" label-width="0" prop="basicBackground" v-if="formData.basicBackground === 'img'">
              <div class="line">
                <el-checkbox class="form-label" v-model="formData.basicBackgroundMaskCheck">背景蒙版</el-checkbox>
                <el-input v-model="formData.basicBackgroundMaskColor" placeholder="请输入" clearable :style="{ width: '30%' }"> </el-input>
                <el-color-picker v-model="formData.basicBackgroundMaskColor" size="mini" :style="{ 'margin-right': '20px' }"></el-color-picker>
              </div>
            </el-form-item>
            <el-form-item label="" label-width="0" prop="basicBackground" v-if="formData.basicBackground === 'img'">
              <div class="line">
                <el-checkbox class="form-label" v-model="formData.basicBackgroundMaskOpacityCheck">蒙版透明度</el-checkbox>
                <div class="slider-box">
                  <el-slider v-model="formData.basicBackgroundMaskOpacity"></el-slider>
                </div>
                <span class="desc">{{ formData.basicBackgroundMaskOpacity }}%</span>
              </div>
            </el-form-item>
          </div>
          <div class="panel-block">
            <el-form-item label="公司名称:" prop="companyName">
              <el-input v-model="formData.companyName" placeholder="请输入公司名称" clearable> </el-input>
            </el-form-item>
            <el-form-item label="字体:" prop="companyFontFamily">
              <el-select class="input-small" v-model="formData.companyFontFamily" placeholder="请选择字体" clearable @change="handleFontFamilyChange">
                <el-option v-for="item in fontOptionList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体颜色:" prop="companyFontColor">
              <div class="line">
                <el-input class="input-small" v-model="formData.companyFontColor" placeholder="请输入字体颜色" clearable> </el-input>
                <el-color-picker v-model="formData.companyFontColor" size="mini" :style="{ 'margin-right': '20px' }"></el-color-picker>
              </div>
            </el-form-item>
            <el-form-item label="字体大小:" prop="companyFontSize">
              <div class="line">
                <el-input type="number" class="input-small" @change="handleOnChange('')" v-model="formData.companyFontSize" placeholder="请输入字体大小" clearable>
                  <template slot="append">px</template>
                </el-input>
                <div class="font-style bold" :class="{ active: formData.companyFontBold }" @click="formData.companyFontBold = !formData.companyFontBold">B</div>
                <div class="font-style italic" :class="{ active: formData.companyFontItalic }" @click="formData.companyFontItalic = !formData.companyFontItalic">I</div>
              </div>
            </el-form-item>
          </div>
          <div class="panel-block">
            <el-form-item label="联系信息:" prop="contactName">
              <el-input v-model="formData.contactName" placeholder="请输入联系信息" clearable> </el-input>
            </el-form-item>
            <el-form-item label="字体:" prop="contactFontFamily">
              <el-select class="input-small" v-model="formData.contactFontFamily" placeholder="请选择字体" clearable @change="handleFontFamilyChange">
                <el-option v-for="item in fontOptionList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体颜色:" prop="contactFontColor">
              <div class="line">
                <el-input class="input-small" v-model="formData.contactFontColor" placeholder="请输入字体颜色" clearable> </el-input>
                <el-color-picker v-model="formData.contactFontColor" size="mini" :style="{ 'margin-right': '20px' }"></el-color-picker>
              </div>
            </el-form-item>
            <el-form-item label="字体大小:" prop="contactFontSize">
              <div class="line">
                <el-input type="number" class="input-small" @change="handleOnChange('')" v-model="formData.contactFontSize" placeholder="请输入字体大小" clearable>
                  <template slot="append">px</template>
                </el-input>
                <div class="font-style bold" :class="{ active: formData.contactFontBold }" @click="formData.contactFontBold = !formData.contactFontBold">B</div>
                <div class="font-style italic" :class="{ active: formData.contactFontItalic }" @click="formData.contactFontItalic = !formData.contactFontItalic">I</div>
              </div>
            </el-form-item>
            <el-form-item label="上方间距:" prop="contactMarginTop">
              <el-input type="number" class="input-small" v-model="formData.contactMarginTop" placeholder="请输入上方间距" clearable>
                <template slot="append">px</template>
              </el-input>
            </el-form-item>
          </div>
          <div class="panel-block">
            <el-form-item label="" label-width="0" prop="descNewPage">
              <div class="line">
                <el-checkbox class="form-label" v-model="formData.descNewPage">广告语展示到第2页</el-checkbox>
              </div>
            </el-form-item>
            <el-form-item label="广告语:" prop="desc">
              <el-input v-model="formData.desc" type="textarea" placeholder="请输入广告语" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
            </el-form-item>
            <el-form-item label="字体:" prop="descFontFamily">
              <el-select class="input-small" v-model="formData.descFontFamily" placeholder="请选择字体" clearable @change="handleFontFamilyChange">
                <el-option v-for="item in fontOptionList" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="字体颜色:" prop="descFontColor">
              <div class="line">
                <el-input class="input-small" v-model="formData.descFontColor" placeholder="请输入字体颜色" clearable> </el-input>
                <el-color-picker v-model="formData.descFontColor" size="mini" :style="{ 'margin-right': '20px' }"></el-color-picker>
              </div>
            </el-form-item>
            <el-form-item label="字体大小:" prop="descFontSize">
              <div class="line">
                <el-input type="number" class="input-small" @change="handleOnChange('descFontSize')" v-model="formData.descFontSize" placeholder="请输入字体大小" clearable>
                  <template slot="append">px</template>
                </el-input>
                <div class="font-style bold" :class="{ active: formData.descFontBold }" @click="formData.descFontBold = !formData.descFontBold">B</div>
                <div class="font-style italic" :class="{ active: formData.descFontItalic }" @click="formData.descFontItalic = !formData.descFontItalic">I</div>
              </div>
            </el-form-item>
            <el-form-item label="行高:" prop="descLineHeight">
              <el-input type="number" class="input-small" @change="handleOnChange('descLineHeight')" v-model="formData.descLineHeight" placeholder="请输入行高" clearable> </el-input>
            </el-form-item>
            <el-form-item v-if="!formData.descNewPage" label="上方间距:" prop="descMarginTop">
              <el-input type="number" class="input-small" v-model="formData.descMarginTop" placeholder="请输入上方间距" clearable>
                <template slot="append">px</template>
              </el-input>
            </el-form-item>
            <el-form-item label="上下边距:" prop="descPaddingTopBottom">
              <el-input type="number" class="input-small" @change="handleOnChange('descPaddingTopBottom')" v-model="formData.descPaddingTopBottom" placeholder="请输入左右边距" clearable>
                <template slot="append">px</template>
              </el-input>
            </el-form-item>
            <el-form-item label="左右边距:" prop="descPaddingLeftRight">
              <el-input type="number" class="input-small" @change="handleOnChange('descPaddingLeftRight')" v-model="formData.descPaddingLeftRight" placeholder="请输入上下边距" clearable>
                <template slot="append">px</template>
              </el-input>
            </el-form-item>
          </div>
          <el-form-item label-width="0" size="large" :style="{ 'margin-top': '20px' }">
            <div class="line" :style="{ width: '100%', justifyContent: 'center' }">
              <el-button size="mini" @click="resetForm" type="info"> 重置 </el-button>
              <el-button size="mini" @click="createGif" type="success" :disabled="!formData.descNewPage" title="生成.gif需要两张及以上图片"> 生成.gif </el-button>
              <el-button size="mini" @click="createJpg" type="primary"> 生成.jpg </el-button>
              <el-button size="mini" @click="handleSaveTemplate" type="primary"> 保存模板 </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 效果预览 -->
      <div class="panel-container right-panel" ref="rightPanel">
        <div class="panel-content" ref="rightPanelContent">
          <div class="panel-title">效果预览</div>
          <div class="image-container" ref="imageContent">
            <div class="image-content">
              <DomToImage ref="DomToImage1" dom-id="DomToImage1" :title="formData.companyName" @createImageDone="handleCreateImageDone" @done="downloadImageDone">
                <div class="image-panel image-1" :style="imagePanelStyle" id="DomToImage1">
                  <div v-if="formData.basicBackground === 'img' && formData.basicBackgroundMaskCheck" class="mask" :style="maskStyle"></div>
                  <div class="content" :style="!formData.descNewPage && descPanelStyle">
                    <div class="text-company" :style="companyStyle">
                      {{ formData.companyName || '请输入公司名称' }}
                    </div>
                    <div class="text-contact" :style="contactStyle">{{ formData.contactName || '请输入联系信息' }}</div>
                    <div v-if="!formData.descNewPage" class="text-desc" :style="descStyle">{{ formData.desc || '请输入广告语' }}</div>
                  </div>
                </div>
              </DomToImage>
              <template v-if="formData.descNewPage">
                <DomToImage v-for="(item, index) in descList" :key="index" :ref="'DomToImage2' + index" :dom-id="'DomToImage2' + index" :title="formData.companyName + index" @createImageDone="handleCreateImageDone" @done="downloadImageDone">
                  <div class="image-panel" :style="imagePanelStyle" :id="'DomToImage2' + index">
                    <div v-if="formData.basicBackground === 'img' && formData.basicBackgroundMaskCheck" class="mask" :style="maskStyle"></div>
                    <div class="content-padding" :style="descPanelStyle">
                      <div class="content" :id="'descContent' + index">
                        <div class="text-desc" :style="descStyle">{{ item || '请输入广告语' }}</div>
                      </div>
                    </div>
                  </div>
                </DomToImage>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!--  保存模板-->
    <el-dialog title="保存模板" :visible.sync="showSaveTemplate">
      <SaveTemplate :loading="loading" :editMode="editMode" :defaultTitle="detail.temp_title" v-if="showSaveTemplate" @close="showSaveTemplate = false" @submit="handleSaveTemplateSubmit" />
    </el-dialog>
  </div>
</template>

<script>
import { apiCreateGif, apiTempAdd, apiTempDetail, apiTempEdit } from '@/api/adManage'
import { uploadImgApi } from '@/api/wxapplet'
import DomToImage from './components/DomToImage.vue'
import ColorPicker from './components/ColorPicker.vue'
import SaveTemplate from './components/SaveTemplate.vue'
import { defaultConfig, defaultForm, fontList, gradientList, fieldList } from './config.js'
import { formatFormData } from '@/utils'

export default {
  name: 'index',
  components: { DomToImage, ColorPicker, SaveTemplate },
  data() {
    return {
      showSaveTemplate: false,
      defaultConfig,
      defaultForm,
      fontList,
      gradientList,
      loading: false,
      formData: { ...defaultForm },
      rules: {
        basicWidth: [{ required: true, message: '请输入尺寸', trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        contactName: [{ required: true, message: '请输入联系信息', trigger: 'blur' }],
      },
      fileList: [],
      fontOptionList: [],
      descList: [],
      currentIndex: 0,
      descCopy: '',
      uploadImgList: [],
      newPage: true,
      rightScrollTop: 0,
      timer: null,
      changeCount: 0,
      changeState: 'init',
      createPoster: false, // 是否正在生成封面海报
      tempTitle: '',
      queryId: '',
      editMode: 'add',
      detail: {},
    }
  },
  watch: {
    'formData.desc': {
      immediate: true,
      handler(val) {
        this.$nextTick(() => {
          this.handleOverflow()
        })
      },
    },
    'formData.descFontFamily': {
      immediate: true,
      handler() {
        this.$nextTick(() => {
          this.handleOverflow()
        })
      },
    },
    'formData.descNewPage': {
      immediate: true,
      handler(val) {
        this.setPanelHeight()
        if (val) {
          // 换页
          this.$nextTick(() => {
            this.handleOverflow()
          })
        }
      },
    },
  },
  computed: {
    imagePanelStyle() {
      const { basicWidth, basicHeight, basicBackground, basicBackgroundColorType, basicBackgroundColor, basicBackgroundImg } = this.formData
      const style = {
        width: (basicWidth || this.defaultConfig.basicWidth) + 'px',
        height: (basicHeight || this.defaultConfig.basicHeight) + 'px',
      }
      if (basicBackground === 'color') {
        if (basicBackgroundColorType === 'single') {
          style.background = basicBackgroundColor
        } else {
          const colorList = basicBackgroundColor.split(',')
          style.background = `linear-gradient(135deg, ${colorList[0]}, ${colorList[1]})`
        }
      } else if (basicBackgroundImg) {
        style.backgroundImage = `url(${basicBackgroundImg.replace(/^(http)[s]*(\:\/\/)/, 'https://images.weserv.nl/?url=')})`
        style.backgroundRepeat = 'no-repeat'
        style.backgroundSize = 'cover'
        style.backgroundPosition = 'center'
      }
      return style
    },
    descPanelStyle() {
      const { descPaddingTopBottom, descPaddingLeftRight } = this.formData
      const style = {}
      if (descPaddingTopBottom) {
        style.paddingTop = style.paddingBottom = descPaddingTopBottom + 'px'
      }
      if (descPaddingLeftRight) {
        style.paddingLeft = style.paddingRight = descPaddingLeftRight + 'px'
      }
      return style
    },
    maskStyle() {
      const { basicBackgroundMaskCheck, basicBackgroundMaskColor, basicBackgroundMaskOpacityCheck, basicBackgroundMaskOpacity } = this.formData
      const style = {}
      if (basicBackgroundMaskCheck) {
        style.background = basicBackgroundMaskColor
      }
      if (basicBackgroundMaskOpacityCheck) {
        style.opacity = basicBackgroundMaskOpacity + '%'
      }
      return style
    },
    companyStyle() {
      const { companyFontFamily, companyFontSize, companyFontColor, companyFontBold, companyFontItalic } = this.formData
      const style = {
        fontFamily: companyFontFamily,
        fontSize: companyFontSize + 'px',
        color: companyFontColor,
      }
      if (companyFontBold) {
        style.fontWeight = 'bold'
      }
      if (companyFontItalic) {
        style.fontStyle = 'italic'
      }
      return style
    },
    contactStyle() {
      const { contactFontFamily, contactFontSize, contactFontColor, contactMarginTop, contactFontBold, contactFontItalic } = this.formData
      const style = {
        fontFamily: contactFontFamily,
        fontSize: contactFontSize + 'px',
        color: contactFontColor,
        marginTop: contactMarginTop + 'px',
      }
      if (contactFontBold) {
        style.fontWeight = 'bold'
      }
      if (contactFontItalic) {
        style.fontStyle = 'italic'
      }
      return style
    },
    descStyle() {
      const { descFontFamily, descFontSize, descFontColor, descFontBold, descFontItalic, descNewPage, descMarginTop, descLineHeight } = this.formData
      const style = {
        fontFamily: descFontFamily,
        fontSize: descFontSize + 'px',
        color: descFontColor,
        lineHeight: descLineHeight,
      }
      if (descFontBold) {
        style.fontWeight = 'bold'
      }
      if (descFontItalic) {
        style.fontStyle = 'italic'
      }
      if (!descNewPage) {
        style.marginTop = descMarginTop + 'px'
      }
      return style
    },
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.fontOptionList = this.fontList
        .filter((item) => {
          if (item.type === 'system') {
            // 系统，监测是否可用
            return this.isSupportFontFamily(item.value)
          } else {
            // 自定义，按需加载
            return true
          }
        })
        .map((item) => {
          return {
            label: item.label,
            value: item.value,
          }
        })

      const query = this.$route.query
      this.queryId = query.id
      this.editMode = query.editMode || 'add'
      if (this.editMode === 'edit' || this.editMode === 'copy') {
        this.getDetail()
      } else {
        this.resetForm()
      }
    },
    // 获取详情
    getDetail() {
      apiTempDetail(formatFormData({ id: this.queryId })).then((res) => {
        if (res.code !== 200) return
        this.detail = res.data
        this.setDetail(res.data)
      })
    },
    // 设置详情
    setDetail(data) {
      let list = ['is_two_page', 'is_company_bold', 'is_contact_bold', 'is_ad_bold', 'is_company_xt', 'is_contact_xt', 'is_ad_xt']
      for (let key in fieldList) {
        if (key === 'is_backcolor_or_img') {
          this.formData[fieldList[key]] = parseInt(data[key]) === 1 ? 'color' : 'img'
        } else if (list.includes(key)) {
          this.formData[fieldList[key]] = parseInt(data[key]) === 1 ? true : false
        } else if (fieldList[key]) {
          this.formData[fieldList[key]] = data[key]
        }
      }

      if (data.back_mask === '') {
        this.formData.basicBackgroundMaskCheck = false
        this.formData.basicBackgroundMaskColor = '#000000'
      }
      if (data.mask_tm_val === 101) {
        this.formData.basicBackgroundMaskOpacityCheck = false
        this.formData.basicBackgroundMaskOpacity = 50
      }
      if (this.formData.basicBackgroundColor.includes(',')) {
        this.formData.basicBackgroundColorType = 'gradient'
      }
      if (!this.formData.basicBackgroundImg || this.formData.basicBackgroundImg === 'null') {
        this.formData.basicBackgroundImg = null
      }
      if (this.formData.descNewPage) {
        this.descList = ['']
      }
      if (this.formData.basicBackground === 'color') {
        this.handleBackgroundColorInput(this.formData.basicBackgroundColor)
      }
      const { companyFontFamily, contactFontFamily, descFontFamily } = this.formData
      this.handleFontFamilyChange(companyFontFamily)
      this.handleFontFamilyChange(contactFontFamily)
      this.handleFontFamilyChange(descFontFamily)
    },
    setPanelHeight() {
      this.$nextTick(() => {
        let leftPanel = this.$refs.leftPanel
        let rightPanel = this.$refs.rightPanel
        if (!leftPanel || !rightPanel) {
          return
        }
        rightPanel.style.height = leftPanel.offsetHeight + 'px'
      })
    },
    handleOverflow() {
      // 防抖
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        // 记录scrollTop
        const rightPanel = this.$refs.rightPanel
        this.rightScrollTop = rightPanel.scrollTop
        this.descCopy = this.formData.desc
        this.currentIndex = -1 // 当前的页数
        this.descList = []
        this.initDesePage()
        // 计算大概字符数
        const containerW = this.formData.basicWidth - this.formData.descPaddingLeftRight * 2
        const containerH = this.formData.basicHeight - this.formData.descPaddingTopBottom * 2
        const fontWidth = this.formData.descFontSize
        const lineHeight = this.formData.descFontSize * this.formData.descLineHeight
        const lineCount = parseInt(containerH / lineHeight)
        const preLineCount = parseInt(containerW / fontWidth)
        const textCount = preLineCount * lineCount
        this.isOverFlow(textCount)
      }, 500)
    },
    isOverFlow(textCount) {
      const domToImage2 = window['descContent' + this.currentIndex]
      if (!domToImage2 || this.descCopy.length === 0) {
        return
      }
      let scrollHeight = domToImage2.scrollHeight
      let offsetHeight = domToImage2.offsetHeight
      if (this.newPage) {
        // 新的一页，先把估算的字数放进去
        this.newPage = false
        this.setDeseList(textCount)
      } else {
        // 检测是否溢出
        if (scrollHeight <= offsetHeight) {
          // 没有溢出,往上加，加到溢出，减回来，变成1再加，加到溢出，减回来
          if (this.descCopy.length === 0) {
            // 没有可以加的了，完成
            this.setDescDone()
            return
          } else {
            this.changeState = 'add'
            if (this.descCopy.length < this.changeCount) {
              this.changeCount = this.descCopy.length
            }
            this.setDeseList(this.changeCount)
          }
        } else {
          // 溢出，往下减，减到不溢出
          if (this.changeState === 'init') {
            // 初始化直接就溢出了
            this.setDeseList(this.changeCount * -1)
          } else {
            this.setDeseList(this.changeCount * -1)
            if (this.changeCount > 1) {
              // 10个加到溢出了，减掉10个，改成1个
              this.changeCount = 1
            } else {
              this.initDesePage()
            }
          }
        }
      }
      this.$nextTick(() => {
        this.isOverFlow(textCount)
      })
    },
    setDeseList(count) {
      if (count > 0) {
        this.$set(this.descList, this.currentIndex, this.descList[this.currentIndex] + this.descCopy.substring(0, count))
        this.descCopy = this.descCopy.substring(count)
      } else {
        const length = this.descList[this.currentIndex].length
        this.descCopy = this.descList[this.currentIndex].substr(count) + this.descCopy
        this.$set(this.descList, this.currentIndex, this.descList[this.currentIndex].substring(0, length + count))
      }
    },
    // 完成广告语一页的计算,初始化参数
    initDesePage() {
      this.descList.push('')
      this.currentIndex++
      this.changeCount = 10 // 加减字数
      this.changeState = 'init' // 加减方向
      this.newPage = true
    },
    // 显示详情内容完成，滚动回原来的位置
    setDescDone() {
      const length = this.descList.length
      if (this.descList[length - 1].length === 0 && length > 1) {
        this.descList.pop()
      }
      this.$refs.rightPanel.scrollTop = this.rightScrollTop
    },
    // 生成gif
    createGif() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        this.loading = true
        this.$refs.DomToImage1.createImage(0)
        if (this.formData.desc.length > 0 && this.formData.descNewPage) {
          for (let i = 0; i <= this.currentIndex; i++) {
            this.$refs['DomToImage2' + i][0].createImage(i + 1)
          }
        }
      })
    },
    // 生成jpg
    createJpg() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        this.loading = true
        this.$refs.DomToImage1.downloadImage()
        if (this.formData.desc.length > 0 && this.formData.descNewPage) {
          for (let i = 0; i <= this.currentIndex; i++) {
            this.$refs['DomToImage2' + i][0].downloadImage()
          }
        }
      })
    },
    // 生成完成
    downloadImageDone() {
      this.loading = false
    },
    handleCreateImageDone({ url, index }) {
      if (this.createPoster) {
        // 生成封面图
        this.createPoster = false
        this.uploadPoster(url)
      } else {
        this.uploadImgList.push({ url, index })
        const length = this.uploadImgList.length
        if (length === this.currentIndex + 2) {
          this.jpgCreateGif()
        }
      }
    },
    // 上传jpg生成gif
    jpgCreateGif() {
      const files = this.uploadImgList
        .sort((a, b) => a.index - b.index)
        .map((item, index) => {
          return this.base64ToFile(item.url, index)
        })
      apiCreateGif(this.jsToFormData({ files })).then((res) => {
        this.loading = false
        this.downloadFile(res, this.formData.companyName)
        this.uploadImgList = []
      })
    },
    downloadFile(res, name) {
      const url = window.URL.createObjectURL(new Blob([res], { type: 'image/gif' }))
      let a = document.createElement('a')
      a.download = name + '.gif' // 文件名
      a.href = url
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    base64ToFile(base64Data, fileName) {
      //将base64转换为blob
      var arr = base64Data.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      const blob = new Blob([u8arr], { type: mime })
      return new File([blob], fileName)
    },
    resetForm() {
      this.formData = { ...defaultForm }
    },
    beforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('图片大小超过 10MB')
      }
      return isRightSize
    },
    handleUpload(file) {
      uploadImgApi(formatFormData({ file: file.file })).then((res) => {
        this.formData.basicBackgroundImg = res.data.url
        this.formData.basicBackground = 'img'
      })
    },
    jsToFormData(obj) {
      //对象转formdata格式
      let formData = new FormData()
      for (var key in obj) {
        if (Array.isArray(obj[key])) {
          obj[key].map((item) => {
            formData.append(key, item)
          })
        } else {
          formData.append(key, obj[key])
        }
      }
      return formData
    },
    // 选择字体
    handleFontFamilyChange(value) {
      let option = this.fontList.find((item) => item.value === value)
      if (!option) {
        return
      }
      if (option.type === 'system' || option.download) {
        return
      }
      option.download = true
      option.pathList.forEach((item) => {
        this.downloadFont(value, item.url, item.weight)
      })
    },
    // 下载字体文件
    downloadFont(fontFamily, url, weight) {
      this.$message({
        message: '字体开始加载，请稍后...',
        type: 'success',
      })
      const style = document.createElement('style')
      style.type = 'text/css'
      document.head.appendChild(style)
      const sheet = style.sheet
      sheet.insertRule(`@font-face { font-family: ${fontFamily}; src: url('${url}'); font-weight: ${weight}; }`, 0)
    },
    // 监测字体是否可用
    isSupportFontFamily(f) {
      // f是要检测的字体
      if (typeof f != 'string') {
        return false
      }
      // h是基础字体
      var h = 'Arial'
      if (f.toLowerCase() == h.toLowerCase()) {
        return true
      }
      // 设置一个检测的字符A,看他是否支持f字体
      var e = 'a'
      var d = 100
      var a = 100,
        i = 100
      var c = document.createElement('canvas')
      var b = c.getContext('2d')
      c.width = a
      c.height = i
      b.textAlign = 'center'
      b.fillStyle = 'black'
      b.textBaseline = 'middle'
      var g = function (j) {
        b.clearRect(0, 0, a, i)
        //字体是传入的j,或者是默认的h
        b.font = d + 'px ' + j + ', ' + h
        b.fillText(e, a / 2, i / 2)
        //获取所有的canvas图片信息
        var k = b.getImageData(0, 0, a, i).data
        //k调用数组的 filter方法,筛选符合条件的。改变原数组。
        return [].slice.call(k).filter(function (l) {
          return l != 0
        })
      }
      //返回结果,如果h默认字体和输入待检测字体f.通过g函数检测得到的字符串不一致,说明自提生效
      return g(h).join('') !== g(f).join('')
    },
    // 输入框限制
    handleOnChange(type) {
      if (type === 'basicWidth') {
        const minWidth = Math.max(this.defaultConfig.minWidth, Number(this.formData.descFontSize) + Number(this.formData.descPaddingLeftRight * 2))
        if (this.formData.basicWidth < minWidth) {
          this.formData.basicWidth = minWidth
        }
      }
      if (type === 'basicHeight') {
        const minHeight = Math.max(this.defaultConfig.minHeight, Number(this.formData.descFontSize * this.formData.descLineHeight) + Number(this.formData.descPaddingTopBottom * 2))
        if (this.formData.basicHeight < minHeight) {
          this.formData.basicHeight = minHeight
        }
      }
      if (type === 'descPaddingTopBottom' || type === 'descPaddingLeftRight') {
        const minDescPadding = this.defaultConfig.minDescPadding
        const maxDescPaddingLeftRight = this.formData.basicWidth / 4
        const maxDescPaddingTopBottpm = this.formData.basicHeight / 4
        if (this.formData.descPaddingTopBottom < minDescPadding) {
          this.formData.descPaddingTopBottom = minDescPadding
        } else if (this.formData.descPaddingTopBottom > maxDescPaddingTopBottpm) {
          this.formData.descPaddingTopBottom = maxDescPaddingTopBottpm
        }
        if (this.formData.descPaddingLeftRight < minDescPadding) {
          this.formData.descPaddingLeftRight = minDescPadding
        } else if (this.formData.descPaddingLeftRight > maxDescPaddingLeftRight) {
          this.formData.descPaddingLeftRight = maxDescPaddingLeftRight
        }
      }
      if (type === 'descLineHeight') {
        const minLineHeight = this.defaultConfig.minLineHeight
        const maxLineHeight = ((this.formData.basicHeight - this.formData.descPaddingTopBottom * 2) / this.formData.descFontSize).toFixed(1)
        if (this.formData.descLineHeight < minLineHeight) {
          this.formData.descLineHeight = minLineHeight
        } else if (this.formData.descLineHeight > maxLineHeight) {
          this.formData.descLineHeight = maxLineHeight
        }
      }
      const minFont = this.defaultConfig.minFont
      const maxFont = Math.min(parseInt((this.formData.basicHeight - this.formData.descPaddingTopBottom * 2) / this.formData.descLineHeight), this.defaultConfig.maxFont)
      if (this.formData.companyFontSize < minFont) {
        this.formData.companyFontSize = minFont
      }
      if (this.formData.contactFontSize < minFont) {
        this.formData.contactFontSize = minFont
      }
      if (this.formData.descFontSize < minFont) {
        this.formData.descFontSize = minFont
      }
      if (this.formData.descFontSize > maxFont) {
        this.formData.descFontSize = maxFont
      }
      const list = ['basicWidth', 'basicHeight', 'descFontSize', 'descPaddingTopBottom', 'descPaddingLeftRight', 'descLineHeight']
      if (list.includes(type)) {
        this.$nextTick(() => {
          this.handleOverflow()
        })
      }
    },
    // 背景色
    handleBackgroundConfirm({ type, value }) {
      this.formData.basicBackgroundColorType = type
      this.formData.basicBackgroundColor = value
    },
    // 输入背景色
    handleBackgroundColorInput(val) {
      if (val.includes(',')) {
        this.formData.basicBackgroundColorType = 'gradient'
        this.$refs.ColorPicker.setValue('gradient', { id: -1, list: val.split(',') })
      } else {
        this.formData.basicBackgroundColorType = 'single'
        this.$refs.ColorPicker.setValue('single', val)
      }
    },
    // 保存模板
    handleSaveTemplate() {
      this.showSaveTemplate = true
    },
    // 保存模板提交
    handleSaveTemplateSubmit(temp_title) {
      this.tempTitle = temp_title
      this.getPosterImg()
    },
    // 获取封面图
    getPosterImg() {
      this.createPoster = true
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        this.loading = true
        this.$refs.DomToImage1.createImage(0, 'file')
      })
    },
    // 上传封面图
    uploadPoster(file) {
      uploadImgApi(formatFormData({ file })).then((res) => {
        if (res.code !== 200) return
        let submitData = {}
        submitData.temp_title = this.tempTitle
        submitData.img_url = res.data.url
        let list = ['is_two_page', 'is_company_bold', 'is_contact_bold', 'is_ad_bold', 'is_company_xt', 'is_contact_xt', 'is_ad_xt']
        for (let key in fieldList) {
          if (key === 'is_backcolor_or_img') {
            submitData[key] = this.formData[fieldList[key]] === 'color' ? 1 : 2
          } else if (list.includes(key)) {
            submitData[key] = this.formData[fieldList[key]] ? 1 : 0
          } else if (fieldList[key]) {
            submitData[key] = this.formData[fieldList[key]]
          }
        }
        if (!this.formData.basicBackgroundMaskCheck) {
          submitData.back_mask = ''
        }
        if (!this.formData.basicBackgroundMaskOpacityCheck) {
          submitData.mask_tm_val = 101
        }

        if (this.editMode === 'add' || this.editMode === 'copy') {
          apiTempAdd(formatFormData(submitData)).then((res) => {
            if (res.code !== 200) {
              this.loading = false
            } else {
              this.showSaveSuccess()
            }
          })
        } else if (this.editMode === 'edit') {
          submitData.id = this.queryId
          apiTempEdit(formatFormData(submitData)).then((res) => {
            if (res.code !== 200) {
              this.loading = false
            } else {
              this.showSaveSuccess()
            }
          })
        }
      })
    },
    showSaveSuccess() {
      this.$message({
        message: '保存成功',
        type: 'success',
      })
      setTimeout(() => {
        this.loading = false
        this.$bus.$emit('closeSelectedTag', this.$route)
      }, 1000)
    },
  },
}
</script>

<style scoped lang="scss">
.page-content {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
}
.el-upload__tip {
  line-height: 1.2;
}
.panel-container {
  padding: 24px 16px;
}
.left-panel {
  width: 35%;
  margin-right: 10px;
  overflow: visible;
}
.right-panel {
  width: 65%;
  overflow: auto;
}
.line {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.input-medium {
  width: 50%;
}
.input-small {
  width: 45%;
}
.panel-block {
  width: 100%;
  padding: 10px;
  background: #f0f1f4;
  margin-top: 10px;
  border-radius: 6px;
}
.el-radio {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.el-color-picker {
  height: 28px !important;
}
::v-deep .el-input-group__append {
  height: 28px !important;
}
::v-deep .el-color-picker__trigger {
  width: 28px !important;
  height: 28px !important;
}
.img-background {
  width: 28px;
  height: 28px;
  object-fit: cover;
}
.el-icon-picture {
  font-size: 24px;
}
.el-radio {
  margin-right: 0px;
}
.el-form-item {
  margin-bottom: 10px;
}
.el-form-item:last-child {
  margin-bottom: 0;
}
.image-container {
  padding: 20px;
}
.image-panel {
  width: 708px;
  height: 316px;
  background: #000000;
  border-radius: 4px;
  margin-bottom: 30px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  position: relative;
  .mask {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
  }
  .content {
    width: 100%;
    height: 100%;
    position: relative;
    z-index: 1;
  }
  &.image-1 {
    .content {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
  }
  .text-company {
    font-size: 30px;
    color: green;
    text-align: center;
  }
  .text-contact {
    font-size: 20px;
    color: #ffffff;
    text-align: center;
    margin-top: 50px;
    white-space: pre-wrap;
  }
  .text-desc {
    width: 100%;
    height: 100%;
    font-size: 16px;
    color: #ffffff;
    white-space: pre-wrap;
    text-align: justify;
  }
}
.font-style {
  font-size: 20px;
  padding: 0 5px;
  color: #aaaaaa;
  cursor: pointer;
  &.bold {
    font-weight: bold;
    margin-left: 10px;
  }
  &.italic {
    font-style: italic;
  }
  &.active {
    color: #333333;
  }
}
.form-label {
  width: 100px;
}
.slider-box {
  flex-grow: 1;
  margin: 0 10px;
}
.el-radio-group {
  width: 100%;
}
::v-deep .el-radio__label,
::v-deep .el-checkbox__label {
  font-size: 14px;
  color: #606266;
  line-height: 28px;
  font-weight: 700;
}
.content-padding {
  width: 100%;
  height: 100%;
}
.color-picker {
  width: 28px;
  height: 28px;
  margin-right: 20px;
}
</style>
<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}
</style>
